package com.jd.service.impl;


import com.jd.dao.DetailDao;
import com.jd.dao.OrderDao;
import com.jd.dao.ShopCarDao;
import com.jd.entity.Detail;
import com.jd.entity.Gorder;
import com.jd.entity.ShopCar;
import com.jd.service.OrderService;
import com.jd.uitls.UUIDUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2017/9/20/020.
 */
@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderDao orderDao;
    @Autowired
    private ShopCarDao shopCarDao;
    @Autowired
    private DetailDao detailDao;

    public List<Gorder> findByUid(Integer uid) {
        return orderDao.findByUid(uid);
    }

    @Transactional
    public int saveOrder(Gorder gorder) {

        gorder.setOrderId(UUIDUtils.uuid());
        gorder.setStatus(1);
        List<ShopCar> list = shopCarDao.findAllByUid(gorder.getUid());//根据用户id获取购物车商品
        orderDao.saveOrder(gorder);//添加订单

        List<Detail> detailList = new ArrayList<Detail>();
        double price = 0;
        for (ShopCar shopCar : list) {
            Detail detail = new Detail(gorder.getOid(), shopCar.getGoods(), shopCar.getCount());
            detailList.add(detail);
            price += shopCar.getGoods().getGprice() * shopCar.getCount();
        }
        int a = 1 / 0;
        orderDao.updateOrder(price, gorder.getOid());//修改价格
        detailDao.saveInBatch(detailList);//批量添加商品详情
        return shopCarDao.deleteByUid(gorder.getUid());//删除购物车

    }
}
